import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createPage, ajax, base, getBusinessInfo, toast, cardCache, getMultiLang, createPageIcon } from 'nc-lightapp-front';
const { NCRadio, NCCheckbox, NCSelect,NCTooltip, NCDiv, NCUpload, NCButton:Button } = base;
import './index.less';
import BusinessUnitVersionDefaultAllTreeRef from '../../../../uapbd/refer/orgv/BusinessUnitVersionDefaultAllTreeRef';
import GLAccPeriodDefaultTreeGridRef from '../../../refer/voucher/GLAccPeriodDefaultTreeGridRef/index';
import ReferLoader from '../../../public/ReferLoader/index.js';
import { accbookRefcode } from '../../../public/ReferLoader/constants.js';
import TransResultModal from '../../TransResultModal';
import getDefaultAccountBook from '../../../public/components/getDefaultAccountBook.js';
import DatePickerModal from './DatePickerModal';
import BatchTransferModal from './BatchTransferModal';
import { onButtonClick, initTemplate } from '../syncTree/events';
import cacheUtils from '../../trransferHistory/utils/cacheUtils.js';
import { pushToGenVoucher } from '../../../public/common/voucherUtils';
const NCOption = NCSelect.NCOption;
import HeaderArea from '../../../public/components/HeaderArea';
import UploadActionModal from '../../../public/components/UploadActionModal';
import buSecondRefer from '../utils/buSecondRefer.js'
class SelfExecute extends Component {
	constructor(props) {
		super(props);
		let defaultAccouontBook = getDefaultAccountBook(props.getSearchParam('c'));

		this.state = {
			isProject: false, //是否按方案过滤
			datePicker: '', //制单日期
			configs: {}, //参照需要
			bizPeriod: '', //业务日期
			pk_unitState: false, //
			accountingbook: { refpk: defaultAccouontBook.value, refname: defaultAccouontBook.display },
			accountingbookMore: [],  
			period: {
				refname: '',
				refpk: ''
			},
			includeUntallied: false, //包含未记账
			includeUntailiedDisabled: false, //包含未记账选择框是否可用
			transResult: [], //结果数据
			transArr: [], //转账方案
			pk_unit: null,
			combineInfo: {},
			isMultiple: 'N',
			pk_transfersArr: [],
			selectedTrans: {
				key: '',
				label: ''/* 国际化处理： 结转方案*/
			}, //选定方案
			// json: {},
			showUploadModal:false,
			GL123: false, //是否启用利润中心
		};
		this.uploadActionInfo = {
			action:'',
			data:''
		}
	}
	//获取默认账簿
	queryAppcontext = () => {
		let url = '/nccloud/platform/appregister/queryappcontext.do';
		let data = {
			appcode: this.props.getSearchParam('c')
		};
		let self = this;
		ajax({
			url,
			data,
			success: function(response) {
				const { data, error, success } = response;
				if (success && data) {
					let accountingbook = {
						refname: data.defaultAccbookName,
						refpk: data.defaultAccbookPk
					};
					if (accountingbook.refpk) {
						self.getPkTo(accountingbook);
					}
				} else {
				}
			}
		});
	}

	componentWillMount() {
		// let callback= (json) =>{
		// 	this.setState({
		// 		json:json,
		// 		// selectedTrans: {
		// 		// 	key: '',
		// 		// 	label: json['20020SDTREPAGE-000012']/* 国际化处理： 结转方案*/
		// 		// }, //选定方案
		// 	},()=>{		  
		// 		initTemplate.call(this, this.props);
		// 	})
		// }
		// getMultiLang({moduleId:'20020SDTREPAGE',domainName:'gl',currentLocale:'simpchn',callback});
		// this.props.button.setButtonDisabled(['bath_gen','gen_voucher'], true)
	}
	componentWillReceiveProps(nextProps) {}

	componentDidMount(){
		initTemplate.call(this, this.props);
		this.props.button.setButtonDisabled(['bath_gen','gen_voucher'], true);

		let tempData = cacheUtils.getSearchData()
		let treeData = cacheUtils.getTreeData()
		let tableData = cacheUtils.getTableData()
		let {accountingbook, period, pk_unit, pk_unitState,includeUntallied,transArr,selectedTrans,includeUntailiedDisabled} = this.state
		let pk_book = tempData && tempData.accountingbook ? tempData.accountingbook.refpk : ''
		// let transPorj = ''
		// let transferType = tempData.transferType
		if(tempData){
			accountingbook = {
				refname: tempData.accountingbook ? tempData.accountingbook.refname : '',
				refpk: tempData.accountingbook ? tempData.accountingbook.refpk : ''
			}
			period = {
				refname: tempData.period ? tempData.period.refname : '',
				refpk: tempData.period ? tempData.period.refpk : '',
				value: tempData.period ? tempData.period.value : {}
			}
			pk_unit = {
				refname: tempData.pk_unit ? tempData.pk_unit.refname : '',
				refpk: tempData.pk_unit ? tempData.pk_unit.refpk : ''
			}
			pk_unitState = tempData.pk_unitState
			includeUntallied = tempData.includeUntallied
			transArr = tempData.transArr
			selectedTrans = tempData.selectedTrans
			// transPorj = tempData.selectedTrans.key
			includeUntailiedDisabled = tempData.includeUntailiedDisabled
			this.setState({
				// transferType,
				accountingbook,
				period,
				pk_unit,
				pk_unitState,
				includeUntallied,
				transArr,
				selectedTrans,
				includeUntailiedDisabled
			});
			
		} else {
			//获取默认账簿
			this.queryAppcontext()
		}
		if(pk_book){
			this.props.getPK(pk_book);
			cacheUtils.setTreeData(treeData)
			cacheUtils.setTableData(tableData)
			if(selectedTrans.key){
				// this.props.onProjectChanged(selectedTrans)
				this.onProjectChanged(selectedTrans)
				setTimeout(() => {
					this.props.onProjectChanged(selectedTrans.key);
				}, 1000);
				
			}
		}
		this.props.SelfExecuteRef(this);	
		
	}

	getProjectStatus(){
		let{isProject}=this.state
		return isProject
	}

	// 更新按钮状态
	updateButtonStatus(disabled,isProject=false){
		let self = this
		//方案结转时，批量结转按钮禁用
		if(isProject){
			self.props.button.setButtonDisabled(['bath_gen'], !disabled)
			self.props.button.setButtonDisabled(['gen_voucher'], disabled)
		} else {
			self.props.button.setButtonDisabled(['bath_gen','gen_voucher'], disabled)
		}
		
	}

	//批量结转
	showBatchTransferModal() {
		let { pk_transfersArr } = this.state;
		let checkData = this.props.getCheckedData();
		pk_transfersArr = [];
		for (let i = 0, len = checkData.length; i < len; i++) {
			pk_transfersArr.push(checkData[i].PK_transfer);
		}
		if (pk_transfersArr.length === 0) {
			toast({ content: this.props.json['20020SDTREPAGE-000013'], color: 'warning' });/* 国际化处理： 请选择要生成的转账定义！*/
			// return false
		} else {
			this.setState({
				pk_transfersArr
			}, ()=>{
				this.BatchTransferModal.show();
			});
		}
	}

	//批量结转确认
	handleBatchTransferOK = (v) => {
		let { accountingbook, period, pk_unit, includeUntallied, pk_transfersArr } = this.state;
		let pk_accountingbooksArr = [];
		for (let i = 0, len = v.length; i < len; i++) {
			pk_accountingbooksArr.push(v[i].refpk);
		}
		let url = '/nccloud/gl/voucher/batchExecTrans.do';
		let data = {
			pk_transfers: pk_transfersArr,
			currentAccBookPk: accountingbook.refpk,
			pk_accountingbooks: pk_accountingbooksArr,
			year: period.refname.slice(0, 4),
			period: period.refname.slice(5, 7),
			// year: period.value.periodyear.value,
			// period: period.value.accperiodmth.value,
			includeUntallied: includeUntallied,
			pk_unit: pk_unit ? pk_unit.refpk : ''
		};
		ajax({
			url,
			data,
			success: (response) =>{
				const { data, error, success } = response;
				if (success && data) {
					this.setState({
						accountingbookMore: v,
						transResult: data
					});
				} else {
					this.setState({
						accountingbookMore: v,
						transResult: {}
					});
				}
				this.TransResultModal.show();
			}
		});
	};

	//制单日期过滤框
	conformData = () => {
		let { accountingbook, period, includeUntallied, pk_unit } = this.state;
		let pk_transfersArr = this.getCheckedTransferPks();
		// period.refname.slice(0, 4)
		// period.refname.slice(5, 7)
		let data = {
			pk_transfers: pk_transfersArr,
			pk_accountingbook: accountingbook.refpk,
			// year: period.refname.slice(0, 4),
			// period: period.refname.slice(5, 7),
			year: period.value?period.value.periodyear.value:'',
			period: period.value?period.value.accperiodmth.value:'',
			includeUntallied: includeUntallied,
			pk_unit: pk_unit ? pk_unit.refpk : '',
			date: '', //制单日期，方案时必传
			directSave: false //是否直接保存，方案时为true
		};
		return data;
	};

	getCheckedTransferPks = () =>{
		let checkData = this.props.getCheckedData();
		let pk_transfersArr = [];
		for (let i = 0, len = checkData.length; i < len; i++) {
			pk_transfersArr.push(checkData[i].PK_transfer);
		}
		return pk_transfersArr;
	}

	//制单日期过滤框确认
	handleDateOK = (date) => {
		let self = this;
		let { period } = self.state;
		let begindate = period.value ? period.value.begindate.value : '';
		let enddate = period.value ? period.value.enddate.value : '';
		let content = `${this.props.json['20020SDTREPAGE-000015']}${begindate}--${enddate}${this.props.json['20020SDTREPAGE-000016']}！`;/* 国际化处理： 请选择,之间的凭证日期*/
		let currentVal = Date.parse(date) 
		let beginVal = Date.parse(begindate) 
		let endVal = Date.parse(enddate) 
		if (currentVal<beginVal || currentVal>endVal) {
			toast({ content: content, color: 'warning' });
			return false;
		}
		let url = '/nccloud/gl/voucher/genVoucherSorted.do';
		let data = self.conformData();
		data.date = date;
		data.directSave = true;
		ajax({
			url,
			data,
			success: function(response) {
				const { data, error, success } = response;
				if (success && data) {
					toast({ content: data, color: 'success' });
				} else {
				}
			}
		});
	};

	/**
	 * 整理搜索区域数据
	 */
	consSearchData = () => {
		let { accountingbook, period, pk_unit,pk_unitState,includeUntallied,transArr,selectedTrans,includeUntailiedDisabled} = this.state;
		let historyData = {
			transferType: 'gl_transfer',
			accountingbook,
			pk_unit,
			period,
			pk_unitState,
			includeUntallied,
			transArr,
			selectedTrans,
			includeUntailiedDisabled,
		}
		return historyData
	}
	/**
	 * 跳转页面前缓存数据
	 */
	chacheDataBeforGoEvent(){
		let treeData = cacheUtils.getTreeData()
		let tableData = cacheUtils.getTableData()
		let historyData =this.consSearchData()
		cacheUtils.setSearchData(historyData)
		cacheUtils.setTreeData(treeData)
		cacheUtils.setTableData(tableData)
	}
	// 生成凭证
	reduceVoucher = () => {
		let page = this;
		let url = '/nccloud/gl/voucher/execTransBackground.do';
		let data = page.conformData();
		let { isProject, period } = page.state;
		if (isProject) {
			if (page.whenProjectPeriodLegal(period)) {
				page.DatePickerModal.show()
			}
		} else {
			ajax({
				url,
				data,
				success: function(response) {
					page.handleGenVoucher(response);
				}
			});
		}
	};

	handleGenVoucher = (response) => {
		let self = this;
		const { data, error, success } = response;
		if (success) {
			self.chacheDataBeforGoEvent()
			let param = {
				voucher: data,
				titlename: self.props.json['20020SDTREPAGE-000014'],/* 国际化处理： 制单*/
				backUrl: '/',
				backAppCode: self.props.getUrlParam('backAppCode') || self.props.getSearchParam('c'),
				backPageCode: self.props.getUrlParam('backPageCode') || self.props.getSearchParam('p'),
			}
			pushToGenVoucher(self,param);
		} else {
		}
	}

	handleGenVoucherError = (data) => {
		let page = this;
		let msg = data && data.error && data.error.message;
		toast({content:msg, color:'danger'})
		page.setState({showUploadModal:false});
	}

	// 历史数据
	goTransferHistory = () => {		
		this.chacheDataBeforGoEvent()
		this.props.pushTo('/trransferHistory', {});
	}

	/**
	 * 方案结转时校验期间是否合法
	 * 非调整期可以结转
	 * @param {*} period 
	 */
	whenProjectPeriodLegal(period) {
		if (period && period.value && period.value.accperiodmth && period.value.accperiodmth.value) {
			let periodMth = period.value.accperiodmth.value;
			if (periodMth.length === 2 && periodMth !== '00') {
				return true;
			}
		}
		return false;
	}

	createCfg(id, param) {
		//参照方法
		var obj = {
			value: this.state.configs[id] ? this.state.configs[id].value : [],
			onChange: function(val) {
				var temp = Object.assign(this.state.configs[id], { value: val });
				this.setState(Object.assign(this.state.configs, temp));
			}.bind(this)
		};
		this.state.configs[id] = obj;
		var result_param = Object.assign(obj, param);
		return result_param;
	}
	
	getPkTo = (v) => {
		//选择核算账簿后请求
		this.props.getPK(v.refpk);
		this.setState({
			accountingbook: v
		});
		let searchData = this.consSearchData()
		searchData.accountingbook = v
		cacheUtils.setSearchData(searchData)
		let url = '/nccloud/gl/voucher/queryTransProject.do';
		let data = {
			pk_accountingbook: v.refpk
		};
		let self = this;
		ajax({
			url,
			data,
			success: function(response) {
				const { data, error, success } = response;
				if (success && data) {
					// data.push({});
					self.setState({
						transArr: data,
						selectedTrans: {
							key: '',
							label: '' //self.props.json['20020SDTREPAGE-000012']/* 国际化处理： 结转方案*/
						}
					},()=>{
						/* 这里调用方案改变处理函数可能在更新树状态时报错 */
						let {selectedTrans} = self.state
						self.onProjectChanged(selectedTrans)
					});
				} else {
				}
			}
		});

		ajax({
			url: '/nccloud/gl/voucher/queryBookCombineInfo.do', //会计期间等
			data: { pk_accountingbook: v.refpk },
			success: function(response) {
				const { data, error, success } = response;
				if (success && data) {
					let period = self.state.period;
					period.refname = data.bizPeriod;
					// period.refpk = data.bizPeriod;
					period.refpk = data.pk_accperiodmonth;
					period.value = {
						periodyear: { value: data.bizPeriod.split('-')[0] },
						accperiodmth: { value: data.bizPeriod.split('-')[1] },
						begindate: { value: data.begindate },
						enddate: { value: data.enddate }
					};
					let pk_unit = {};
					let liabilityCenter = {};
					let combineInfo = data;
					self.setState({
						period,
						combineInfo,
						pk_unitState: data.isShowUnit,
						GL123: data.GL123,
						pk_unit,
						liabilityCenter 
					});
				} else {
				}
			}
		});
	};

	// 改变结转方案
	onProjectChanged(v) {
		let page = this;
		page.setState({
			selectedTrans: v
		})
		let searchData = this.consSearchData()
		searchData.selectedTrans = v
		cacheUtils.setSearchData(searchData)
		let { includeUntallied, includeUntailiedDisabled, isProject } = page.state;
		if(typeof v.key == 'undefined' || typeof v.label == 'undefined'|| !v.label || !v.key){
			includeUntailiedDisabled = false;
			includeUntallied = false;
			isProject = false;
			// page.props.onProjectChanged();
		} else{
			includeUntallied = true;
			includeUntailiedDisabled = true;
			isProject = true;
			// page.props.onProjectChanged(v.key);
		}
		page.setState({ includeUntailiedDisabled, includeUntallied, isProject });
	}
	closeResultModal = () => {
		let {transResult} = this.state;
		let {json} = this.props;
		if (transResult.vouchers) {
			this.chacheDataBeforGoEvent()
			let param = {
				voucher: transResult.vouchers,
				titlename: json['20020SDTREPAGE-000014'],/* 国际化处理： 制单*/
				backUrl: '/',
				backAppCode: this.props.getUrlParam('backAppCode') || this.props.getSearchParam('c'),
				backPageCode: this.props.getUrlParam('backPageCode') || this.props.getSearchParam('p'),
			}
			pushToGenVoucher(this,param);
		}
	}
	renderCountingBookRef() {
		let { accountingbook, isMultiple } = this.state;
		let accountTtip = `财务核算账簿:${accountingbook.refname ?accountingbook.refname : ''}`
		return (
			<ReferLoader
				tag="accbook"
				fieldid='accountingbook'
				tip={accountTtip}
				isMultiSelectedEnabled={isMultiple === 'Y' ? true : false}
				refcode={accbookRefcode}
				showGroup={false}
				showTitle={false}
				showInCludeChildren={true}
				value={{ refname: accountingbook.refname, refpk: accountingbook.refpk }}
				disabledDataShow = {true}
				queryCondition={{
					appcode: this.props.getSearchParam('c'),
					TreeRefActionExt: 'nccloud.web.gl.ref.AccountBookRefSqlBuilder'
				}}
				onChange={(v) => {
					this.getPkTo(v);
				}}
			/>	
		);
	}
	renderRedio() {
		let { isMultiple } = this.state;
		let {json} = this.props;
		return (
			<NCRadio.NCRadioGroup
				name="fruit"
				selectedValue={isMultiple}
				onChange={(v) => {
					isMultiple = v;
					this.setState({
						isMultiple
					});
				}}
			>
				<NCRadio value="N">{json['20020SDTREPAGE-000017']}</NCRadio>{/* 国际化处理： 单选*/}
				<NCRadio value="Y">{json['20020SDTREPAGE-000018']}</NCRadio>{/* 国际化处理： 多选*/}
			</NCRadio.NCRadioGroup>
		);
	}

	render() {
		let {
			accountingbook,
			accountingbookMore,
			period,
			includeUntallied,
			pk_unitState,
			transResult,
			transArr,
			pk_unit,
			combineInfo,
			includeUntailiedDisabled,
			isMultiple,
			isProject,
			showUploadModal,
			GL123
		} = this.state;
		let {json, modal} = this.props;
		let page = this;
		let buziInfo = getBusinessInfo();
		let unitTip = (<div>{`业务单元:${pk_unit && pk_unit.refpk ? pk_unit.refname : ''}`}</div>)
		let periodTip = (<div>{`会计期间:${period.refname ? period.refname : ''}`}</div>)
		let uploadActionInfo = page.uploadActionInfo;
		let secondReferType = GL123 ? 'liabilityCenter' : 'pk_unit'; //二级账簿:利润中心/业务单元,二选一显示，或均不显示
		return (
			<div>
				<HeaderArea 
					title = {this.props.getSearchParam('n')}
					btnContent = {this.props.button.createButtonApp({
						area: 'page_header',
						onButtonClick: onButtonClick.bind(this),
						popContainer: document.querySelector('.btn-group')
					})}
				/>
				<NCDiv areaCode={NCDiv.config.SEARCH} className='search-area'>
					<div className="header-refer">
						{ this.renderCountingBookRef() }
					</div>
					<NCTooltip trigger="hover" placement="top" inverse={true} overlay={unitTip}>
						<div className={pk_unitState ? 'header-refer' : 'display-none'}>
							{pk_unitState ?
								buSecondRefer(this,{
									referType: secondReferType, 
									pk_accountingbook: accountingbook.refpk, 
									onChangeCallBack: (v)=>{this.props.loadAllTransDef(accountingbook.refpk,v.refpk)},
								}) : ''
							}
						</div>
					</NCTooltip>
					
					<NCTooltip trigger="hover" placement="top" inverse={true} overlay={periodTip}>
						<div className="header-refer">
							{GLAccPeriodDefaultTreeGridRef(
								(this.createCfg('GLAccPeriodDefaultTreeGridRef', {
									value: {
										refname: period.refname,
										refpk: period.refpk
									},
									showTitle:false,
									fieldid: 'period',
									queryCondition: () => {
										let condition = {
											pk_accountingbook: accountingbook.refpk,
											showPeriodInit: 'Y',
											pk_accperiodscheme: combineInfo.pk_accperiodscheme,
											includeAdj:'Y'
										};
										return condition;
									},
									onChange: (v) => {
										period.refname = v.refname;
										period.refpk = v.refpk;
										period.value = v.values;
										this.setState({
											period
										});
									}
								}))
							)}
						</div>
					</NCTooltip>
					
					<div className="header-item">
						<NCCheckbox
							colors="info"
							checked={includeUntallied}
							disabled={includeUntailiedDisabled}
							onChange={(v) => {
								includeUntallied = v;
								page.setState({
									includeUntallied
								});
							}}
						>
							{json['20020SDTREPAGE-000019']}{/* 国际化处理： 包含未记账凭证*/}
						</NCCheckbox>				
					</div>
					<div className="header-item">
						<span className='nc-theme-common-font-c'>{json['20020SDTREPAGE-000020']}：</span>{/* 国际化处理： 执行方案*/}
						<NCSelect
							labelInValue={true}
							fieldid='transproject'
							placeholder={json['20020SDTREPAGE-000012']} /* 国际化处理： 结转方案*/
							value={this.state.selectedTrans}	
							onChange={(v) => {
								if(typeof v == 'undefined'){
									v = {key: undefined, label: undefined}
								}
								page.onProjectChanged(v);
								page.props.onProjectChanged(v.key);
							}}
						>
							{/* <NCOption value='' disabled={true}>{json['20020SDTREPAGE-000012']}</NCOption>国际化处理： 结转方案 */}
							{transArr.map((item, index) => {
								return <NCOption value={item.m_pk_transproject}>{item.m_transprojectname}</NCOption>;
							})}
						</NCSelect>
					</div>
				</NCDiv>
				{/* 批量结果弹出框 */}
				<TransResultModal
					modal = {modal}
					transResult={transResult}
					handleCancel={this.closeResultModal}
					TransResultModalRef = {init => this.TransResultModal = init}
				/> 
				{/* 日期 */}
				<DatePickerModal
					modal = {modal}
					handleDateOK={this.handleDateOK.bind(this)}
					period={period}
					DatePickerModalRef = {init => this.DatePickerModal = init}
				/>
				{/* 批量结转弹框 */}
				<BatchTransferModal
					modal = {modal}
					context={{ appcode: this.props.getSearchParam('c') }}
					handleBatchTransferOK={this.handleBatchTransferOK.bind(this)}
					BatchTransferModalRef = {init => this.BatchTransferModal = init}
				/> 
				<UploadActionModal
					title="包含Excel取数函数，请上传Excel文件"
					show={showUploadModal}
					action={uploadActionInfo.action}
					data = {uploadActionInfo.data}
					handleDone={uploadActionInfo.handleSuccess}
					handleError={uploadActionInfo.handleError}
					handleClose={() => {page.setState({showUploadModal:false})}}
				/>
			</div>
		);
	}
}

SelfExecute = createPage({
})(SelfExecute);
export default SelfExecute;
